import aclApi from "@/api/aclUser";

const state = {
  aclList: [],
  total: 0,
  userAclList: {},
};
const mutations = {
  SET_ACLLISTTOTAL(state, aclDataList) {
    state.aclList = aclDataList;
  },
  SET_TOTAL(state, total) {
    console.log(total)
    state.total = total;
  },
  SET_USERACLLIST(state, userAclList) {
    state.userAclList = userAclList;
  },
};
const actions = {
  // 获取信息
  async getAclListTotal({ commit }, { page, limit, searchName }) {
    try {
      let res = await aclApi.getUserPage(page, limit, searchName);
      commit("SET_ACLLISTTOTAL", res.items);
      commit("SET_TOTAL", res.total);
    } catch (error) {
      return Promise.reject(new Error("请求获取页数显示失败"));
    }
  },
  // 修改保存
  async saveAclOrUpdate({ commit }, saveData) {
    console.log(saveData)
    try {
      await aclApi.saveAclOrUpdate(saveData);
      return "OK";
    } catch (error) {
      return Promise.reject(new Error("请求添加or修改失败"));
    }
  },
  // 多删
  async removeAllAcl({ commit,dispatch }, idList) {
    // try {
    //   await aclApi.batchRemove(idList);//失效,需要调用单个删除的方法
    //   return "ok"
    // } catch (error) {
    //   return Promise.reject(new Error("请求全删失败"));
    // }
    let res = []
    idList.forEach(async item => {
      let r = dispatch("removeOnAcl",item)
      res.push(r)
    });
    try {
      let success = await Promise.all(res)
      console.log(success,"全删成功")
        return "ok"
    } catch (error) {
      return Promise.reject(new Error("请求全删失败"));
      
    }
  },
  // 单删
  async removeOnAcl({ commit }, id) {
    try {
      await aclApi.removeAcl(id);
      return "OK";
    } catch (error) {
      return Promise.reject(new Error("请求单删失败"));
    }
  },
  // 更具用户获取角色数据
  async getAclData({ commit }, userId) {
    try {
      let res = await aclApi.getAclData(userId);
      commit("SET_USERACLLIST", res);
      return "Ok";
    } catch (error) {
      return Promise.reject(new Error("请求更具用户获取角色失败"));
    }
  },
//  添加用户角色
async setDoAssign({commit},{userId, roleId}){
    try {
        let res = roleId.join(",")
        await aclApi.doAssign(userId,res)
        // return "Ok";
    } catch (error) {
      return Promise.reject(new Error("请求添加用户角色失败"));
        
    }
}
};
export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
